package com.luocc.ccdemo.ui

import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.luocc.ccdemo.R
import com.luocc.ccdemo.vm.UserViewModel

class MineFragment : Fragment() {
    private lateinit var mFavorites: ViewGroup
    private lateinit var mDownload: ViewGroup
    private lateinit var mUserViewModel: UserViewModel
    private lateinit var mLogoutDialog: AlertDialog
    private lateinit var mContext: Context

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "onCreate: ")
        mUserViewModel = ViewModelProvider(this).get(UserViewModel::class.java)
        mUserViewModel.getLogoutResult().observe(this) {
            findNavController().navigate(R.id.action_mine_fragment_to_loginFragment)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val parent = inflater.inflate(R.layout.fragment_mine, container, false)
        mLogoutDialog = AlertDialog.Builder(parent.context)
            .setMessage("确定要退出登录吗?")
            .setNegativeButton("取消") { _, _ -> }
            .setPositiveButton("确定") { _, _ ->
                logout()
            }.create()
        mFavorites = parent.findViewById(R.id.favorites_layout)
        mDownload = parent.findViewById(R.id.download_layout)
        val accountPicture = parent.findViewById<ImageButton>(R.id.account_picture)
        val logout = parent.findViewById<ViewGroup>(R.id.logout_layout)
        mFavorites.setOnClickListener {
            findNavController().navigate(R.id.action_mine_fragment_to_videoFavoritesFragment)
        }

        mDownload.setOnClickListener {
            findNavController().navigate(R.id.action_mine_fragment_to_videoFavoritesFragment)
        }

        logout.setOnClickListener {
            mLogoutDialog.show()
        }

        accountPicture.setOnClickListener {
            findNavController().navigate(R.id.action_mine_fragment_to_loginFragment)
        }
        return parent
    }

    private fun logout() {
        // FIXME: 加一个dialog
        mUserViewModel.logout()
    }

    companion object {
        private const val TAG = "LC_MineFragment"
    }
}